﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using System.Diagnostics;
using WatiN.Core.Constraints;

namespace WatiN.Sharepoint.WebControls
{
    /// <summary>
    /// A default Sharepoint listview is rendered as a table element with class='ms-listviewtable'
    /// </summary>
    public class BaseSPList : Control<Table>
    {
        /// <summary>
        /// ElementConstraint to 'find' BaseSPList's
        /// </summary>
        public override Constraint ElementConstraint
        {
            get
            {
                return Find.ByClass("ms-listviewtable");
            }
        }


        private List<HeaderColumn> _columns = null;

        /// <summary>
        /// Columns shown in the list
        /// </summary>
        public List<HeaderColumn> Columns 
        {
            get
            {
                if (_columns == null)
                {
                    SetColumns();
                }
                return _columns;
            }
        }

        /// <summary>
        /// Set the columns field of this list. 
        /// The first <see cref="TableRow"/> of the only <see cref="TableBody"/> contains the <see cref="TableHeaderCell"/> items.
        /// </summary>
        private void SetColumns()
        {
            _columns = new List<HeaderColumn>();

            TableRow headerRow = this.Element.TableBodies[0].TableRows[0];
            var headerColumns = headerRow.ElementsOfType<TableHeaderCell>();

            for (int index = 0; index < headerColumns.Count(); index++)
            {
                _columns.Add(new HeaderColumn(headerColumns[index], index));
            }
        }
    }
}
